package com.cangsan.erhai.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WechatAuthenticationFilter  extends AbstractAuthenticationProcessingFilter {


    public WechatAuthenticationFilter(){
        super(new AntPathRequestMatcher("/wx/login", "POST"));

    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        Map<String, Object> param = getParam(request.getReader());
        String loginCode = (String) param.get("loginCode");
        String phoneCode = (String) param.get("phoneCode");
        String nickName = (String) param.get("nickName");
        String imageUrl = (String) param.get("imageUrl");

        WechatAuthenticationToken authRequest = new WechatAuthenticationToken(loginCode,phoneCode,nickName,imageUrl);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    public Map<String,Object> getParam(BufferedReader br){
        Map<String,Object> params = new HashMap<String, Object>();

        try {

            String str, wholeParams = "";
            while((str = br.readLine()) != null){
                wholeParams += str;
            }
            if(StringUtils.isNotBlank(wholeParams)){
                params = JSON.parseObject(wholeParams,Map.class);
            }
        } catch (IOException e) {
            logger.error("",e);
        }
        return  params;
    }
}
